package model

import (
	"encoding/json"

	"chat.com/pkg/snowflake"
	"gorm.io/gorm"
	"gorm.io/plugin/soft_delete"
)

// 单聊好友关系
type SingleFriend struct {
	Id        int64                 `json:"id" gorm:"type:bigint; primaryKey"` // 主键自增id
	CreatedAt int64                 `json:"created_at" gorm:"type:bigint; not null; default CURRENT_TIMESTAMP"`
	UpdatedAt int64                 `json:"updated_at" gorm:"type:bigint; not null; default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP"`
	DeletedAt soft_delete.DeletedAt `json:"deleted_at" gorm:"type:bigint; not null; default 0"`

	UserId    int64 `json:"user_id"     gorm:"type:bigint;      not null;  uniqueIndex:idx_friendship,priority:1;  comment:'用户id'"`
	FriendId  int64 `json:"friend_id"   gorm:"type:bigint;      not null;  uniqueIndex:idx_friendship,priority:2;  comment:'好友id'"`
	IsSpecial int64 `json:"is_special"  gorm:"type:tinyint(1);  not null;  default 0;  comment:'是否特别关心'"`
}

// 群
type Group struct {
	Id        int64                 `json:"id" gorm:"type:bigint; primaryKey"` // 主键自增id
	CreatedAt int64                 `json:"created_at" gorm:"type:bigint; not null; default CURRENT_TIMESTAMP"`
	UpdatedAt int64                 `json:"updated_at" gorm:"type:bigint; not null; default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP"`
	DeletedAt soft_delete.DeletedAt `json:"deleted_at" gorm:"type:bigint; not null; default 0"`

	Name               string `json:"name"           gorm:"type:varchar(100);  not null;  comment:'群名称'"`
	FounderId          int64  `json:"founder_id"     gorm:"type:bigint;        not null;  comment:'创建者id'"`
	Admins             string `json:"admins"         gorm:"type:json;          not null;  comment:'管理员们'"`
	FoundedTime        int64  `json:"founded_time"   gorm:"type:bigint;        not null;  comment:'创建时间'"`
	LatestInternalRank int64  `json:"latest_internal_rank"  gorm:"type:smallint;    not null;  comment:'当前最大组内序号'"`
	IsShutup           int64  `json:"is_shutup"      gorm:"type:tinyint(1);  not null;  default 0;  comment:'是否全员禁言中'"`
}

// 群成员
type GroupMember struct {
	Id        int64                 `json:"id" gorm:"type:bigint; primaryKey"` // 主键自增id
	CreatedAt int64                 `json:"created_at" gorm:"type:bigint; not null; default CURRENT_TIMESTAMP"`
	UpdatedAt int64                 `json:"updated_at" gorm:"type:bigint; not null; default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP"`
	DeletedAt soft_delete.DeletedAt `json:"deleted_at" gorm:"type:bigint; not null; default 0"`

	GroupId      int64 `json:"group_id"       gorm:"type:bigint;      not null;  uniqueIndex:idx_group_member,priority:1;  comment:'群id'"`
	MemberId     int64 `json:"member_id"      gorm:"type:bigint;      not null;  uniqueIndex:idx_group_member,priority:2;  comment:'成员id'"`
	InternalRank int64 `json:"internal_rank"  gorm:"type:smallint;    not null;  comment:'组内序号'"`
	LastSentId   int64 `json:"last_sent_id"   gorm:"type:bigint;      not null;  default 0;  comment:'最后一次获取成功的群消息id'"`
	LastReadId   int64 `json:"last_read_id"   gorm:"type:bigint;      not null;  default 0;  comment:'最后一次已读的群消息id'"`
	IsAdmin      int64 `json:"is_admin"       gorm:"type:tinyint(1);  not null;  default 0;  comment:'是否是管理员'"`
	IsShutup     int64 `json:"is_shutup"      gorm:"type:tinyint(1);  not null;  default 0;  comment:'是否禁言中'"`
}

// 新建一条好友关系
func NewSingleFriend(userId, friendId int64) error {

	friendShip := SingleFriend{
		//Model:    BaseModel{Id: snowflake.Snowflaker.Generate().Int64()},
		UserId:   userId,
		FriendId: friendId,
	}

	if err := db.Create(&friendShip).Error; err != nil {
		return err
	}

	return nil
}

// 获取所有好友
func GetAllSingleFriend(userId int64) (singleFriends []SingleFriend, err error) {

	if err := db.Where("user_id = ?", userId).Find(&singleFriends).Error; err != nil {
		return nil, err
	}

	return
}

// 判断是否是好友
func IsSingleFriend(userId, friendId int64) (ok bool, err error) {

	var singleFriend SingleFriend
	if err = db.Where("user_id = ? and friend_id = ?", userId, friendId).Find(&singleFriend).Error; err != nil {
		return false, err
	}

	/*if singleFriend.Model.Id == 0 {
		return false, nil
	}*/

	if err = db.Where("user_id = ? and friend_id = ?", friendId, userId).Find(&singleFriend).Error; err != nil {
		return false, err
	}

	/*if singleFriend.Model.Id == 0 {
		return false, nil
	}*/

	return true, nil
}

// 删除好友
func DeleteSingleFriend(userId, friendId int64) (ok bool, err error) {

	if err = db.Where(
		"user_id = ? and friend_id = ?", userId, friendId).Or(
		"user_id = ? and friend_id = ?", friendId, userId).Delete(&SingleFriend{}).Error; err != nil {

		return false, err
	}

	return true, nil
}

// 新建一个群
func NewGroup(name string, founderId int64, content string, senderId int64, recieverId int64, sentTime int64) (id int64, err error) {

	admins, err := json.Marshal([]int64{founderId})
	if err != nil {
		return 0, err
	}

	id = snowflake.Snowflaker.Generate().Int64()

	group := Group{
		Id:          id,
		Name:        name,
		FounderId:   founderId,
		Admins:      string(admins),
		FoundedTime: senderId,
	}

	if err := db.Create(&group).Error; err != nil {
		return 0, err
	}

	return id, nil
}

// 全员禁言
func ShutUpGroup(groupId int64) (err error, msg string) {

	res := db.Model(&Group{}).Where("id = ?", groupId).Update("is_shutup", 1)
	if res.Error != nil {
		return res.Error, "禁言失败"
	}

	if res.RowsAffected == 0 {
		return nil, "已经被禁言了"
	}

	return nil, "该群被禁言"
}

// 是否全员禁言
func IsShutUpGroup(groupId int64) (ok bool, err error) {

	var group Group
	if err := db.Where("id = ?", groupId).Find(&group).Error; err != nil {
		return false, err
	}

	if group.Id == 0 {
		return false, gorm.ErrRecordNotFound
	}

	if group.IsShutup == 0 {
		return false, nil
	}

	return true, nil
}

// 删除群
func DeleteGroup(groupId int64) (ok bool, err error) {

	if err = db.Where("id = ?", groupId).Delete(&Group{}).Error; err != nil {
		return false, err
	}

	return true, nil
}

// 新建一个群成员
func NewGroupMember(groupId int64, memberId int64) (id int64, err error) {

	tx := db.Begin()

	id = snowflake.Snowflaker.Generate().Int64()

	member := &GroupMember{
		Id:       id,
		GroupId:  groupId,
		MemberId: memberId,
	}

	if err = tx.Create(&member).Error; err != nil {
		tx.Rollback()
		return 0, err
	}

	tx.Commit()
	return id, nil
}

// 获取所有群成员
func GetGroupMember(groupId int64) (groupMembers []GroupMember, err error) {

	if err := db.Where("group_id = ?", groupId).Find(&groupMembers).Error; err != nil {
		return nil, err
	}

	return
}

// 判断用户是否是群成员
func IsGroupMember(groupId, memberId int64) (ok bool, err error) {

	var groupMember GroupMember
	if err := db.Where("group_id = ? and member_id = ?", groupId, memberId).Find(&groupMember).Error; err != nil {
		return false, err
	}

	if groupMember.Id == 0 {
		return false, nil
	}

	return true, nil
}

// 禁言群成员
func ShutUpGroupMember(groupId, memberId int64) (err error, msg string) {

	res := db.Model(&GroupMember{}).Where("group_id = ? and member_id = ?", groupId, memberId).Update("is_shutup", 1)
	if res.Error != nil {
		return res.Error, "禁言失败"
	}

	if res.RowsAffected == 0 {
		return nil, "已经被禁言了"
	}

	return nil, "该成员被禁言"
}

// 群成员是否被禁言
func IsShutUpGroupMember(groupId, memberId int64) (ok bool, err error) {

	var groupMember GroupMember
	if err := db.Where("group_id = ? and member_id = ?", groupId, memberId).Find(&groupMember).Error; err != nil {
		return false, err
	}

	if groupMember.Id == 0 {
		return false, gorm.ErrRecordNotFound
	}

	if groupMember.IsShutup == 0 {
		return false, nil
	}

	return true, nil
}

// 删除群成员
func DeleteGroupMember(groupId, memberId int64) (ok bool, err error) {

	if err = db.Where("group_id = ? and member_id", groupId, memberId).Delete(&GroupMember{}).Error; err != nil {
		return false, err
	}

	return true, nil
}
